package com.hsh.servlet.user;/**
 * @author xrkhy
 * @date 2025/6/27 9:41
 * @description
 */

import com.alibaba.fastjson2.JSONObject;
import com.hsh.pojo.User;
import com.hsh.service.UserService;
import com.hsh.service.impl.UserServiceImpl;
import com.hsh.utils.JsonResultUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet(name = "login", value = "/login")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // post请求读取 json格式
        request.setCharacterEncoding("utf-8");
        // 读取 json
        String json = request.getReader().readLine();
        User user = JSONObject.parseObject(json, User.class);
        UserService userService = new UserServiceImpl();
        User user1 = userService.login(user);
        if (user1 != null){
            if(!(user1.getRole().equals(user.getRole()))){
                String jsonMassage = JsonResultUtil.buildResult(500, "权限不足", null);
                response.getWriter().write(jsonMassage);
                return;
            }
            // user1转成 json
            String jsonMassage = JsonResultUtil.buildResult(200, "登录成功", user1);
            // 存储到 session
            request.getSession().setAttribute("user", user1);

            System.out.println(request.getSession().getAttribute("user"));
            System.out.println("登录成功");
            response.getWriter().write(jsonMassage);
        }else {
            String jsonMassage = JsonResultUtil.buildResult(500, "登录失败", null);
            response.getWriter().write(jsonMassage);
            System.out.println("登录失败");
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
